<template>
   <div class="full-page-image" :style="containerStyle">
      <div class="transparent-overlay right-aligned" :style="!isOption ? 'top:45% !important' : ''">
         <!-- 登录框开始 -->
         <div class="login-box">
            <div class="logo"> <img :src="siteConfig.login_page.logo_box" alt="Logo" class="login-logo"
                  style="cursor: pointer;" /></div>
            <div class="login" v-if="isOption">
               <label class="label" for="phone">手机号</label>
               <input type="text" v-model="loginForm.username" ref="mobileInputRef" placeholder="请输入手机号"
                  class="login-input" />
               <label class="label" for="password">密码</label>
               <input type="password" v-model="loginForm.password" ref="passwordInputRef" placeholder="请输入密码"
                  class="login-input" />
               <label class="label" for="auth-code">授权码</label>
               <input type="text" v-model="loginForm.auth_code" ref="authCodeInputRef" placeholder="请输入授权码"
                  class="login-input" />
            </div>
            <div class="reg" v-else>
               <label class="label" for="phone">公司名称</label>
               <input type="text" ref="regCompanyInputRef" placeholder="请输入公司名称" v-model="regForm.company"
                  class="login-input" />
               <label class="label" for="resource">公司地址</label>
               <input type="text" ref="regCompanyInputRef" placeholder="请输入公司地址" v-model="regForm.resource"
                  class="login-input" />
               <label class="label" for="phone">联系人电话</label>
               <input type="text" ref="regMobileInputRef" v-model="regForm.mobile" placeholder="请输入手机号"
                  class="login-input" />
               <label class="label" for="phone">联系人</label>
               <input type="text" v-model="regForm.name" placeholder="请输入联系人" ref="regNameInputRef"
                  class="login-input" />
               <label class="label" for="phone">扫码联系客服开通专属账号</label>
               <div style="text-align: left;"> <el-image style="width: 100px; height: 100px;;margin-top: 10px;"
                     :src="siteConfig.login_page.customer_ewm" preview-teleported
                     :preview-src-list="[siteConfig.login_page.customer_ewm]" fit="cover" />
               </div>

            </div>
            <div style="text-align: right;margin-top: 10px;" v-if="isOption">
               <el-text style="cursor: pointer; color: #fff;" tag="ins" @click="tabClick">没有账号,去注册</el-text>
            </div>
            <div style="text-align: right;margin-top: 10px;" v-else>
               <el-text style="cursor: pointer; color: #fff;" tag="ins" @click="tabClick">已有账号,去登录</el-text>
            </div>
            <div class="login-buttons" v-if="isOption">
               <el-button class="login-button" :class="isOption ? 'btn_active' : ''"
                  @click.stop="loginClick">登录</el-button>
            </div>
            <div class="login-buttons" v-else>
               <el-button class="register-button" :class="!isOption ? 'btn_active' : ''"
                  @click.stop="regClick">注册</el-button>
            </div>
         </div>
         <!-- 登录框结束 -->
      </div>
      <!-- 视频轮播模块 -->
      <div class="v-container" ref="scrollContainer" @wheel="handleManualScroll" @touchstart.passive="handleTouchStart"
         @touchmove.passive="handleTouchMove">
         <div class="video">
            <div v-for="(item, index) in [...videoArr, ...videoArr]" :key="index" class="video_mok" @mouseenter="pauseScroll"
               @mouseleave="resumeScroll">
               <div class="video-cover" @click="videoClick(item)">
                  <el-image :src="item.url" style="width: 100%; height: 100%" fit="cover" />
                  <div class="ptn"></div>
               </div>
            </div>
         </div>
      </div>
      <!-- 视频轮播模块end -->
      <!-- <div class="video">
         <div class="video_mok" v-for="i in 10">
            <div class="video-cover" @click="videoClick">我是视频封面
               <div class="ptn"></div>
            </div>
         </div>
      </div> -->
      <div class="page-footer">

         <div class="footer-logo">
            <img :src="siteConfig.login_page.footer_logo" alt="Footer Logo" style="cursor: pointer;" />
         </div>
         <div class="footer-text">
            <p>Copyright © 2024 - 2025 All rights reserved. {{ siteConfig.site_name }} ©版权所有 <a style="color: #fff;"
                  href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank" rel="nofollow">{{
                     siteConfig.record_number }} </a></p>
         </div>
         <div class="footer-text">
            <p>{{ siteConfig.login_page.footer_text }}</p>
         </div>
      </div>
   </div>


   <el-dialog custom-class="custom-dialog" :show-close="false" :style="{
      '--dialog-bg': '#424242',
      'background': 'var(--dialog-bg)',
   }" v-model="dialogVisible" @opened="handleOpened" @closed="handleClosed" destroy-on-close>
      <template #header="{ close, titleId, titleClass }">
         <div class="my-header" style="display: flex; justify-content: space-between;">
            <div>
               <h4 :id="titleId" :class="titleClass" style="color: #f15a24;">{{ dialogTitle }}</h4>
            </div>
            <div><div style="cursor: pointer;" @click="close"><el-icon color="black" :size="20" class="el-icon--left"><CloseBold /></el-icon></div></div>
         </div>
      </template>
      <VideoPlayer v-if="dialogVisible && validatedUrl" :video-url="validatedUrl" :should-play="dialogVisible"
         :end-background="validatedImg" autoplay @ended="handleVideoEnd" />
   </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, watchEffect, watch } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { doLogin, videoList, webSiteConfig } from '../api/home/index'
import { saveCustomer } from "../api/product";
import router from '../router'
import VideoPlayer from '@/components/VideoPlayer.vue'

import { useUserInfo } from '../stores/userInfo'
import { useSiteConfig } from '../stores/siteConfig';
import { title } from 'process';
const userInfo = useUserInfo() //获取用户信息
const siteConfig = useSiteConfig()

const containerStyle = computed(() => ({
   '--bg-image': `url(${siteConfig.login_page.login_img})`,
}));

//配置文件
webSiteConfig().then((res: any) => {
   if (res.code === 1) {
      siteConfig.dataFill(res.data.list)
   }
});
// 自定义验证规则
const validatePhoneNumber = (value: string): boolean => {
   const phoneRegex = /^(1[3-9]\d{9})$|^(0\d{2,3}-?\d{7,8})$/;
   return phoneRegex.test(value);
};
const itemCount = 10 // 实际元素数量
const scrollContainer = ref<HTMLElement | null>(null)
const scrollInterval = ref<number | null>(null)
const isScrolling = ref(true)
const scrollSpeed = ref(1)
const isManualScrolling = ref(false)
const touchStartX = ref(0)
const originalWidth = ref(0)
//视频点击
const dialogTitle = ref('视频弹窗')
const dialogVisible = ref(false)
const rawVideoUrl = ref('')
const validatedImg = ref('')
const validatedUrl = computed(() => {
   return rawVideoUrl.value?.startsWith('http') ? rawVideoUrl.value : null
})
const handleOpened = () => {
   if (!validatedUrl.value) {
      ElMessage.error('无效的视频地址')
      dialogVisible.value = false
   }
}
//点击事件
const videoClick = (item: any) => {
   dialogVisible.value = true
   dialogTitle.value = item.title
   rawVideoUrl.value = item.video_url
   validatedImg.value = item.url
}
const handleClosed = () => {
   rawVideoUrl.value = ''
}

const handleVideoEnd = (url: string) => {
   console.log('视频播放完成')
}

const onReady = () => {
   console.log('播放开始')
}

const onError = (err: Error) => {
   dialogVisible.value = false
   ElMessage.error(`播放失败: ${err.message}`)
}
// 自动滚动逻辑
const startAutoScroll = () => {
   if (scrollInterval.value) return
  
  const container = scrollContainer.value
  if (!container) return
  // 计算原始内容宽度
  originalWidth.value = container.scrollWidth / 2
  const animate = () => {
    if (!isScrolling.value || !container) {
      scrollInterval.value = requestAnimationFrame(animate)
      return
    }
    
    // 无缝循环逻辑
    if (container.scrollLeft >= originalWidth.value) {
      container.scrollLeft = 0
    } else {
      container.scrollLeft += scrollSpeed.value
    }
    
    scrollInterval.value = requestAnimationFrame(animate)
  }

   scrollInterval.value = requestAnimationFrame(animate)
}

// 计算原始内容宽度
const calculateWidth = () => {
   if (scrollContainer.value) {
      originalWidth.value = scrollContainer.value.scrollWidth / 2
   }
}

// 控制方法
const pauseScroll = () => {
   isScrolling.value = false
}

const resumeScroll = () => {
  if (!isManualScrolling.value) {
    isScrolling.value = true
  }
}

// 事件处理
const handleManualScroll = (e:any) => {
  if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
    isManualScrolling.value = true
    pauseScroll()
    setTimeout(() => {
      isManualScrolling.value = false
      resumeScroll()
    }, 2000)
  }
}

const handleTouchStart = (e:any) => {
  touchStartX.value = e.touches[0].clientX
  pauseScroll()
}

const handleTouchMove = (e:any) => {
  const deltaX = e.touches[0].clientX - touchStartX.value
  if (Math.abs(deltaX) > 5) {
    isManualScrolling.value = true
  }
}

const videoArr = ref<any>([]);
const videoListInfo = () => {
   videoList().then((res: any) => {
      console.log(res)
      if (res.code == 1) {
         videoArr.value = res.data.list
      }
   })
}


// 生命周期
onMounted(() => {
   videoListInfo()
   watchEffect(calculateWidth)
   startAutoScroll()
})

onBeforeUnmount(() => {
   if (scrollInterval.value) {
      cancelAnimationFrame(scrollInterval.value)
   }
})
//登录注册切换
const isOption = ref(true)

const tabClick = () => {
   isOption.value = !isOption.value
}
//登录表单
interface LoginForm {
   password: string,
   username: string,
   auth_code: string,
}
const loginForm = reactive<LoginForm>({
   password: '',
   username: '',
   auth_code: '',
})

//注册表单
interface RegForm {
   subscribe_id: number,
   company: string,
   name: string,
   mobile: string,
   resource: string,
   type: number,
}
const regForm = reactive<RegForm>({
   subscribe_id: 0,
   company: '',
   name: '',
   mobile: '',
   resource: '',
   type: 2
})

//登录
const mobileInputRef = ref<InstanceType<typeof import('element-plus').ElInput> | null>(null);
const passwordInputRef = ref<InstanceType<typeof import('element-plus').ElInput> | null>(null);
const authCodeInputRef = ref<InstanceType<typeof import('element-plus').ElInput> | null>(null);
const loginClick = () => {
   if (loginForm.username.trim() === '') {
      ElMessage.error('请输入手机号');
      if (mobileInputRef.value) {
         mobileInputRef.value.focus();
      }
      return;
   }
   if (!validatePhoneNumber(loginForm.username)) {
      ElMessage.error('请输入正确的手机号或固定电话号码，例如：13x12345678或05xx-82xxxxxx');
      if (mobileInputRef.value) {
         mobileInputRef.value.focus();
      }
      return;
   }
   if (loginForm.password.trim() === '') {
      ElMessage.error('请输入密码');
      if (passwordInputRef.value) {
         passwordInputRef.value.focus();
      }
      return;
   }
   // 验证密码长度是否不低于6位
   if (loginForm.password.length < 6) {
      ElMessage.error('密码长度不能低于6位');
      if (passwordInputRef.value) {
         passwordInputRef.value.focus();
      }
      return;
   }
   if (loginForm.auth_code.trim() === '') {
      ElMessage.error('请输入授权码');
      if (authCodeInputRef.value) {
         authCodeInputRef.value.focus();
      }
      return;
   }
   const loading = ElLoading.service({
      lock: true,
      text: '请稍等,正在登录中...',
      background: 'rgba(0, 0, 0, 0.7)',
   })
   doLogin(loginForm).then((res: any) => {
      if (res.code == 1) {
         userInfo.dataFill(res.data.userInfo)
         router.push({ path: res.data.routePath })
      }
   }).catch((error) => {
      if (error.code === 0) {
         ElMessage.error(error.msg)
      } else if (error.code === 'ERR_CANCELED') {
         ElMessage.error("请求错误")
      } else {
         ElMessage.error("未知错误")
      }
   }).finally(() => {
      loading.close()
   });
}

//注册
const regMobileInputRef = ref<InstanceType<typeof import('element-plus').ElInput> | null>(null);
const regNameInputRef = ref<InstanceType<typeof import('element-plus').ElInput> | null>(null);
const regCompanyInputRef = ref<InstanceType<typeof import('element-plus').ElInput> | null>(null);
const regResourceInputRef = ref<InstanceType<typeof import('element-plus').ElInput> | null>(null);
const regClick = () => {
   if (regForm.company.trim() === '') {
      ElMessage.error('请输入公司名称');
      if (regCompanyInputRef.value) {
         regCompanyInputRef.value.focus();
      }
      return;
   }
   if (regForm.resource.trim() === '') {
      ElMessage.error('预计每年的下载量');
      if (regResourceInputRef.value) {
         regResourceInputRef.value.focus();
      }
      return;
   }
   if (regForm.mobile.trim() === '') {
      ElMessage.error('请输入手机号');
      if (regMobileInputRef.value) {
         regMobileInputRef.value.focus();
      }
      return;
   }
   if (!validatePhoneNumber(regForm.mobile)) {
      ElMessage.error('请输入正确的手机号或固定电话号码，例如：13x12345678或05xx-82xxxxxx');
      if (regMobileInputRef.value) {
         regMobileInputRef.value.focus();
      }
      return;
   }
   if (regForm.name.trim() === '') {
      ElMessage.error('请输入联系人');
      if (regNameInputRef.value) {
         regNameInputRef.value.focus();
      }
      return;
   }
   //请求
   const loading = ElLoading.service({
      lock: true,
      text: '请稍等,正在提交...',
      background: 'rgba(0, 0, 0, 0.7)',
   })
   saveCustomer(regForm).then((res: any) => {
      if (res.code == 1) {
         ElMessage.success(res.msg);

         regForm.company = ''
         regForm.name = ''
         regForm.mobile = ''
         regForm.resource = ''
      }
   }).catch((err: any) => {
      ElMessage.error(err.msg);
      console.log(err)
   }).finally(() => {
      loading.close()
   })
}
</script>

<style scoped>
.el-radio.is-bordered.is-checked {
   border-color: #e85623 !important;
}

/* 使用深度选择器穿透scoped样式 */
::v-deep .custom-dialog {
   background-color: #808080 !important;
   /* 灰色背景 */
}

/* 如果需要修改头部背景 */
::v-deep .custom-dialog .el-dialog__header {
   background-color: #808080;
}

/* 修改内容区域背景 */
::v-deep .custom-dialog .el-dialog__body {
   background-color: #808080;
   color: white;
   /* 可选：修改文字颜色保证可读性 */
}

/* 修改遮罩层背景（如果需要） */
::v-deep .el-overlay {
   background-color: rgba(0, 0, 0, 0.7) !important;
}

/* 弹窗内视频容器 */
:deep(.el-dialog__body) {
   padding: 0 !important;
}

/* 视频播放器自适应 */
.video-player {
   width: 100%;
   aspect-ratio: 16/9;
   /* 保持16:9比例 */
}

.el-radio__input.is-checked+.el-radio__label {
   color: #e85623 !important;
}

.el-input__wrapper {
   background-color: #1a1a1a !important;
}

.el-radio__input.is-checked .el-radio__inner {
   background: #e85623 !important;
   border-color: #e85623 !important;
}

.el-radio__label {
   color: #fff;
}

.full-page-image {
   /* 设置div为全屏和其他基本样式 */
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   display: flex;
   align-items: center;
   justify-content: right;

   /* 注意：这里可能需要根据你的布局需求进行调整 */
   z-index: 0;
   /* 通常不需要，除非页面上有其他层需要处理 */
   overflow: hidden;
   /* 防止内容溢出 */
}

.full-page-image::before {
   /* 伪元素用于背景图片和模糊效果 */
   content: "";
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   background-image: var(--bg-image);
   background-size: cover;
   background-position: center;
   background-repeat: no-repeat;
   /*  filter: blur(10px);添加模糊效果 */
   filter: blur(10px) brightness(100%) saturate(0%) contrast(120%);
   z-index: -1;
   /* 确保伪元素位于文字下方 */
}

.login-box {
   /* 设置登录框的样式 */

   border-radius: 8px;
   /* 圆角边框，使登录框看起来更柔和 */
   text-align: center;
   /* 使内容居中，包括 Logo 图片 */
}

.logo {
   display: flex;
   width: 100%;
   justify-content: center;
   margin-bottom: 10px;
}

.login-logo {
   width: 150px;
   /* 设置 Logo 图片的宽度，可以根据需要调整 */
   height: auto;
   /* 高度自动调整以保持图片的宽高比 */
   /*  margin-bottom: 20px;  在 Logo 图片和输入框之间添加一些垂直间距 */
}

.transparent-overlay {
   /* 设置悬浮层为透明，并添加一些内边距和背景色透明度 */
   background-color: rgba(0, 0, 0, 0.5);
   /* 黑色背景，50%透明度 */
   padding: 20px;
   /* 内边距，可根据需要调整 */
   border-radius: 8px;
   /* 可选：圆角边框 */
   width: 390px;
   /* 设定悬浮层的宽度 */
   /* 使用绝对定位将悬浮层放置在页面右侧 */
   position: absolute;
   top: 50%;
   /* 垂直方向居中（需要transform调整） */
   right: 10%;
   /* 距离页面右侧20px */
   transform: translateY(-50%);
   /* 垂直居中调整 */
   /* 可选：设置悬浮层内文字的样式 */
   color: white;
   /* 白色文字，以便在深色背景上更易阅读 */
   text-align: center;
   /* 文字居中（如果悬浮层内容较多，可能需要其他布局） */


}

.login-input {
   /* 设置输入框的样式 */
   width: 100%;
   /* 宽度设置为登录框宽度的100%，再减去左右内边距（假设各20px） */
   padding: 10px;
   /* 内边距 */
   margin: 10px 0;
   /* 上下边距 */
   border: none;
   /* 边框颜色 */
   border-radius: 4px;
   /* 圆角边框 */
   box-sizing: border-box;
   /* 包括内边距和边框在内计算元素的总宽度和高度 */
   background-color: #0f1222;
   /* 灰色背景 */
   color: #fff;
}

.login-input:focus {
   /* 鼠标选中（聚焦）时变为红色背景 */
   background-color: #2c3042;
   /* 红色背景 */
   outline: none;
   /* 移除默认的聚焦边框 */
}

/**
.login-input::-webkit-input-placeholder { 
  text-align: center;
  color: #888;
  opacity: 1;
}

.login-input::-moz-placeholder { 
  text-align: center;
  color: #888;
  opacity: 1;
}

.login-input:-ms-input-placeholder {
  text-align: center;
  color: #888;
  opacity: 1;
}

.login-input::-ms-input-placeholder { 
  text-align: center;
  color: #888;
  opacity: 1;
}

.login-input::placeholder { 
  text-align: center;
  color: #888;
  opacity: 1;
}
*/

.login-buttons {
   /* 设置按钮容器的样式，以便将登录和注册按钮放在同一行上 */
   /* display: flex; */
   /* 使用 flexbox 布局 */
   /* justify-content: space-between; */
   /* 使按钮之间有一定的间距 */
   margin-top: 20px;
   /* 在按钮和输入框之间添加一些垂直间距 */
}

.btn_active {
   background: linear-gradient(90deg, #fab173, #f74018);
}

.login-button,
.register-button {
   /* 设置登录和注册按钮的样式（与之前登录按钮的样式相同，但现在也应用于注册按钮） */
   width: 100%;
   /* 宽度设置为按钮容器宽度的50%，再减去左右间距（这里假设间距为10px，但实际上由 justify-content 控制） */
   padding: 10px;
   /* 内边距 */
   border: none;
   /* 无边框 */
   background-color: #e85623;
   /* 绿色背景 */
   color: white;
   /* 白色文字 */
   cursor: pointer;
   /* 鼠标悬停时显示手型指针 */
   border-radius: 4px;
   /* 圆角边框 */
   font-size: 16px;
   /* 字体大小 */
   box-sizing: border-box;
   /* 包括内边距和边框在内计算元素的总宽度和高度 */
}

/* 可选：为按钮添加悬停效果 */
.login-button:hover {
   background-color: #a02e04;
   color: #fff;
   /* 悬停时背景色变深 */
}

.register-button:hover {
   background-color: #a02e04;
   /* 悬停时背景色变深 */
   color: #fff;
}

.v-container {
   position: fixed;
   bottom: 150px;
   left: 0;
   right: 0;
   overflow-x: auto;
   padding: 10px 30px;
}

.video {
   display: inline-flex;
   white-space: nowrap;
}

.video_mok {
   position: relative;
   display: inline-flex;
   width: 200px;
   height: 80px;
   border: 1px solid #857d7d;
   border-radius: 10px;
   margin: 0 10px;
   flex-shrink: 0;
   cursor: pointer;
   overflow: hidden;
}

.video-cover {
   position: relative;
   width: 100%;
   height: 100%;
   display: flex;
   align-items: center;
   justify-content: center;
   overflow: hidden;
}

.video-cover :deep(.el-image) {
   width: 100%;
   height: 100%;
   transition: transform 0.3s ease;
}

/* 悬停放大效果（可选） */
.video_mok:hover :deep(.el-image) {
   transform: scale(1.05);
}

.ptn {
   position: absolute;
   width: 40px;
   height: 40px;
   opacity: 0;
   transform: scale(0.8);
   transition: all 0.3s ease;
   pointer-events: none;
}

.ptn::before {
   content: '';
   position: absolute;
   width: 100%;
   height: 100%;
   background: rgba(0, 0, 0, 0.6);
   border-radius: 50%;
   animation: pulse 1.5s infinite;
}

.ptn::after {
   content: '';
   position: absolute;
   left: 52%;
   top: 50%;
   transform: translate(-50%, -50%);
   width: 0;
   height: 0;
   border-top: 12px solid transparent;
   border-bottom: 12px solid transparent;
   border-left: 18px solid white;
}

.video_mok:hover .ptn {
   opacity: 1;
   transform: scale(1);
}

@keyframes pulse {
   0% {
      transform: scale(0.95);
   }

   50% {
      transform: scale(1.1);
   }

   100% {
      transform: scale(0.95);
   }
}

/* 悬停效果 */
.video_mok:hover .ptn {
   opacity: 1;
   transform: scale(1);
}

/* 脉冲动画 */
@keyframes pulse {
   0% {
      transform: scale(0.95);
   }

   50% {
      transform: scale(1.1);
   }

   100% {
      transform: scale(0.95);
   }
}

.page-footer {
   position: fixed;
   bottom: 0px;
   left: 0%;
   right: 0%;
   width: 100%;
   color: white;
   /* 文字颜色 */
   display: flex;
   justify-content: space-between;
   align-items: center;
   padding: 10px 150px;
   /* 内边距 */
   box-sizing: border-box;
   /* 包括内边距和边框在内计算元素的总宽度和高度 */
   z-index: 1;
   /* 确保页脚位于其他内容之上 */
}

.footer-logo img {
   height: auto;
   /* 高度自动调整以保持图片的宽高比 */
}

.footer-text p {
   margin: 0;
   /* 移除段落默认的上下边距 */
}

.radio-group {
   display: flex;
   /* 使用Flexbox布局 */
   align-items: center;
   /* 垂直居中（可选） */
   justify-content: space-between;
   border: 1px solid #0f1222;
   padding: 10px 8px;
   margin: 10px 0;
   font-size: 13px;
}

.radio-group>div {
   margin: 0;
   /* 移除可能存在的默认外边距 */
   display: flex;
   align-items: center;
}

.label {
   display: flex;
}
</style>